package com.oa.framework.acc.excuse.service;

import com.oa.common.exception.CreateObjectException;
import com.oa.framework.acc.excuse.dao.AccountExcuseDao;
import com.oa.framework.acc.excuse.domain.AccountExcuse;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountExcuseServiceImpl implements AccountExcuseService, ApplicationContextAware {

    @Autowired
    private AccountExcuseDao excuseDao;
    @Autowired
    private RepositoryService repository;
    @Autowired
    private RuntimeService runtime;

    private ApplicationContext context;


    private final String processDefinitionKey = "excuse";


    @Transactional(rollbackFor = {Exception.class})
    @Override
    public AccountExcuse startExcuseProcess(AccountExcuse excuse) {
        AccountExcuseServiceImpl bean = context.getBean(AccountExcuseServiceImpl.class);
        //查找最匹配的流程
        ProcessDefinition definition = repository.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).latestVersion().singleResult();
        String definitionId = definition.getId();
        System.err.println("请假流程Id:"+definitionId);
        //创建申请单
        AccountExcuse accountExcuse = bean.saveExcuseProcess(excuse);
        //得到businessId后启动流程
        ProcessInstance instance = runtime.startProcessInstanceById(definitionId, accountExcuse.getBusinessKey());
        System.err.println("流程实例Id:"+instance.getId());
        //为申请单赋值
        final int successFlag = 1;
        int set = excuseDao.setProcessInfo(accountExcuse.getExcuseId(), definitionId, instance.getProcessInstanceId());
        if(successFlag == set){
            return accountExcuse;
        }
        throw new CreateObjectException();
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public AccountExcuse startExcuseProcess(Long excuseId) {
        //查找最匹配的流程
        //启动excuseId启动流程
        AccountExcuseServiceImpl bean = context.getBean(AccountExcuseServiceImpl.class);
        return null;
    }

    @Override
    public AccountExcuse saveExcuseProcess(AccountExcuse excuse) {
        int successFlag = 1;
        int insert = this.excuseDao.insert(excuse);
        if(successFlag == insert){
            return excuse;
        }
        throw new  CreateObjectException();
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
